package com.xhg.util.safe;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;

import com.xhg.common.Constants;
import com.xhg.util.propUtil.Prop;
import com.xhg.util.propUtil.PropertiesUtil;

/**
 * MD5加密 (MD5是一种摘要算法不可逆)
 * @createTime 2014-12-18
 * @author wjw
 */
public class MD5Util {
	/**
	 * 初始化加载加密秘钥
	 */
	static{
		Prop prop=PropertiesUtil.loadProperty("config/param.properties",Constants.DEFAULT_ENCODING);
		key=prop.get("md5.key");
	}
	private static final String key;
	private static final Logger log = Logger.getLogger(MD5Util.class);
	public static byte[] getKeyedDigest(byte[] buffer, byte[] key) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(buffer);
			return md5.digest(key);
		} catch (NoSuchAlgorithmException e) {
			log.error(e);
		}
		return null;
	}
    /**
     * 加密
     * @param strSrc需要加密的字符串
     * @param key 密钥
     * @return	加密后密文
     */
	public static String getEncrypt(String str, String key) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(str.getBytes("UTF8"));
			
			StringBuffer result = new StringBuffer();
			byte[] temp;
			temp = md5.digest(key.getBytes("UTF8"));
			for (int i = 0; i < temp.length; i++) {
				result.append(Integer.toHexString(
						(0x000000ff & temp[i]) | 0xffffff00).substring(6));
			}
			return result.toString();

		} catch (NoSuchAlgorithmException e) {
			log.error(e);
		} catch (Exception e) {
			log.error(e);
		}
		return null;
	}
	/**
	 * 加密调用系统默认秘钥
	 * @param str	待加密字符串
	 * @return		加密后密文
	 */
	public static String getEncrypt(String str) {
		return getEncrypt(str,key);
	}
	public static void main(String[] args) {
		String s = "123";//需要加密的字符串
		String key ="hbxhgs2014";//加密秘钥
		// 第二个参数请填空字符串
		String mi = MD5Util.getEncrypt(s);
		String mi2 = MD5Util.getEncrypt(s,key);
		System.out.println(s+"	加密后的密文为		" + mi);
		System.out.println(s+"	加密后的密文为		" + mi2);
	}
}
